package com.atguigu.auth.controller;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.atguigu.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class SMSController {

    @Autowired
    Client client;
    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/send")
    public R sendSms(String phone) throws Exception {

        String key = "USERPH_";
        String code = UUID.randomUUID().toString().substring(0,4);
        redisTemplate.opsForValue().set(key+phone,code,30, TimeUnit.HOURS);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("我的谷粒学院在线教育网站")
                .setTemplateCode("SMS_205138330")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        System.out.println(sendSmsRequest.toString());
        return R.ok().put("sms",sendSmsResponse);
    }
}
